package com.acdc.business.service.impl;

import java.util.List;
import java.util.Date;
import java.math.BigDecimal;
import java.math.RoundingMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.acdc.business.mapper.PowerConsumptionRecordMapper;
import com.acdc.business.domain.PowerConsumptionRecord;
import com.acdc.business.service.IPowerConsumptionRecordService;
import com.acdc.business.service.IRechargeRecordService;
import com.acdc.config.service.IElectricityConfigService;
import com.acdc.device.service.IMeterDeviceService;
import com.acdc.service.IElectricityMeterActivePowerService;
import com.acdc.device.domain.MeterDevice;
import com.acdc.domain.ElectricityMeterActivePower;
import com.ruoyi.system.service.ISysUserService;
import com.acdc.service.IIotModuleService;
import com.acdc.mqtt.service.IotModuleSender;
import com.acdc.wechat.service.WechatRefundService;
import com.acdc.business.domain.RechargeRecord;
import lombok.extern.slf4j.Slf4j;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.acdc.domain.IotModule;
/**
 * 用户用电记录Service业务层处理
 * 
 * @author acdc
 * @date 2025-09-01
 */
@Slf4j
@Service("powerConsumptionRecordService")
public class PowerConsumptionRecordServiceImpl implements IPowerConsumptionRecordService 
{
    @Autowired
    private PowerConsumptionRecordMapper powerConsumptionRecordMapper;

    @Autowired
    private IElectricityMeterActivePowerService electricityMeterActivePowerService;

    @Autowired
    private IElectricityConfigService electricityConfigService;

    @Autowired
    public IMeterDeviceService meterDeviceService;

    @Autowired
    private IRechargeRecordService rechargeRecordService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IIotModuleService iotModuleService;

    @Autowired
    private IotModuleSender iotModuleSender;

    @Autowired
    private WechatRefundService wechatRefundService;

    /**
     * 查询用户用电记录
     * 
     * @param id 用户用电记录主键
     * @return 用户用电记录
     */
    @Override
    public PowerConsumptionRecord selectPowerConsumptionRecordById(Long id)
    {
        return powerConsumptionRecordMapper.selectPowerConsumptionRecordById(id);
    }

    /**
     * 查询用户用电记录列表
     * 
     * @param powerConsumptionRecord 用户用电记录
     * @return 用户用电记录
     */
    @Override
    public List<PowerConsumptionRecord> selectPowerConsumptionRecordList(PowerConsumptionRecord powerConsumptionRecord)
    {
        return powerConsumptionRecordMapper.selectPowerConsumptionRecordList(powerConsumptionRecord);
    }

    /**
     * 新增用户用电记录
     * 
     * @param powerConsumptionRecord 用户用电记录
     * @return 包含主键的用户用电记录
     */
    @Override
    public PowerConsumptionRecord insertPowerConsumptionRecord(PowerConsumptionRecord powerConsumptionRecord)
    {
        powerConsumptionRecord.setCreatedAt(new Date());
        powerConsumptionRecordMapper.insertPowerConsumptionRecord(powerConsumptionRecord);
        return powerConsumptionRecord;
    }

    /**
     * 修改用户用电记录
     * 
     * @param powerConsumptionRecord 用户用电记录
     * @return 结果
     */
    @Override
    public int updatePowerConsumptionRecord(PowerConsumptionRecord powerConsumptionRecord)
    {
        return powerConsumptionRecordMapper.updatePowerConsumptionRecord(powerConsumptionRecord);
    }

    /**
     * 批量删除用户用电记录
     * 
     * @param ids 需要删除的用户用电记录主键
     * @return 结果
     */
    @Override
    public int deletePowerConsumptionRecordByIds(Long[] ids)
    {
        return powerConsumptionRecordMapper.deletePowerConsumptionRecordByIds(ids);
    }

    /**
     * 删除用户用电记录信息
     * 
     * @param id 用户用电记录主键
     * @return 结果
     */
    @Override
    public int deletePowerConsumptionRecordById(Long id)
    {
        return powerConsumptionRecordMapper.deletePowerConsumptionRecordById(id);
    }

    @Deprecated
    @Override
    public PowerConsumptionRecord pending(Long recordId)
    {
        PowerConsumptionRecord record = powerConsumptionRecordMapper.selectPowerConsumptionRecordById(recordId);
        record.setStatus(2L);
        record.setPendingTime(new Date());        
        updateRecord(record);
        powerConsumptionRecordMapper.updatePowerConsumptionRecord(record);
        return record;
    }

    @Override
    public PowerConsumptionRecord finish(Long recordId)
    {
        PowerConsumptionRecord record = powerConsumptionRecordMapper.selectPowerConsumptionRecordById(recordId);
        record.setStatus(0L);
        record.setFinishedTime(new Date());
        updateRecord(record);
        powerConsumptionRecordMapper.updatePowerConsumptionRecord(record);
        // 退款
        RechargeRecord rechargeRecord = rechargeRecordService.selectRechargeRecordByOrderId(record.getOrderId());
        Float amount = rechargeRecord.getAmount();
        if (amount > record.getCost()) {
            
            MeterDevice meterDevice = meterDeviceService.selectMeterDeviceById(record.getMeterId());
            // 关闭电表电源
            IotModule iotModule = iotModuleService.selectIotModuleById(meterDevice.getIotModuleId());
            iotModuleSender.setPwrSta(iotModule.getImei(), 0);
            try {
                // 使用 BigDecimal 避免浮点数精度问题
                BigDecimal amountDecimal = new BigDecimal(amount.toString());
                BigDecimal costDecimal = new BigDecimal(record.getCost().toString());
                BigDecimal refundAmount = amountDecimal.subtract(costDecimal);
                int refundAmountCents = refundAmount.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP).intValue();
                
                wechatRefundService.createRefund(
                    record.getOrderId(),
                    refundAmountCents
                );
            } catch (Exception e) {
                log.error("退款失败: " + e.getMessage(), e);
                throw new RuntimeException("退款失败: " + e.getMessage());
            }
        }
        return record;
    }

    @Deprecated
    @Override
    public PowerConsumptionRecord continueRecord(Long recordId)
    {
        PowerConsumptionRecord record = powerConsumptionRecordMapper.selectPowerConsumptionRecordById(recordId);
        record.setContinueTime(new Date());
        updateRecord(record);
        powerConsumptionRecordMapper.updatePowerConsumptionRecord(record);
        return record;
    }

    @Override
    public void updateRecords()
    {
        try {
            PowerConsumptionRecord query = new PowerConsumptionRecord();
            query.setStatus(1L);
            List<PowerConsumptionRecord> records = powerConsumptionRecordMapper.selectPowerConsumptionRecordList(query);
            for (PowerConsumptionRecord record : records)
            {
                updateRecord(record);
                powerConsumptionRecordMapper.updatePowerConsumptionRecord(record);
            }
        } catch (Exception e) {
            log.error("更新用电记录失败: " + e.getMessage(), e);
        }
    }

    private void updateRecord(PowerConsumptionRecord record)
    {
        MeterDevice meterDevice = meterDeviceService.selectMeterDeviceById(record.getMeterId());
        Float price = electricityConfigService.getElectricityPrice(Long.parseLong(meterDevice.getPrcCode()));
        ElectricityMeterActivePower query = new ElectricityMeterActivePower();
        query.setElectricityMeterId(record.getMeterId());
        query.setCollectionTime(record.getCreatedAt());
        Float energy = 0f;
        List<ElectricityMeterActivePower> list = electricityMeterActivePowerService.selectElectricityMeterActivePowerList(query);
        if (list.size() > 0)
        {
            // 取第一个与最后一个元素的activePower做差，得到使用电量
            energy = list.get(0).getActivePower() - list.get(list.size() - 1).getActivePower();
            record.setEnergy(energy);            
        }
        Date now = new Date();
        float useTime = 0f;
        Date startTime = record.getCreatedAt();
        useTime = (now.getTime() - startTime.getTime()) / 1000 / 60;    
        record.setUseTime(useTime);
        Float cost = energy * price;
        record.setCost(cost);
        // 判断余额是否足够
        RechargeRecord rechargeRecord = rechargeRecordService.selectRechargeRecordByOrderId(record.getOrderId());
        Float amount = rechargeRecord.getAmount();
        if (amount <= cost) {
            // 结束订单
            record.setStatus(0L);
            record.setFinishedTime(now);
            // 更新余额
            SysUser user = userService.selectUserById(record.getUserId());
            user.setBalance(user.getBalance() - cost);
            userService.updateUser(user);
            // 更新充值订单状态
            rechargeRecord.setStatus(2L);
            rechargeRecord.setUpdatedAt(now);
            rechargeRecordService.updateRechargeRecord(rechargeRecord);
            // 关闭电表电源
            IotModule iotModule = iotModuleService.selectIotModuleById(meterDevice.getIotModuleId());
            iotModuleSender.setPwrSta(iotModule.getImei(), 0);
        }
    }

    @Override
    public PowerConsumptionRecord selectPowerConsumptionRecordByOrderId(String orderId)
    {
        return powerConsumptionRecordMapper.selectPowerConsumptionRecordByOrderId(orderId);
    }
}
